<template>
	<view>
		<view class="container" :style="'padding-top: ' + (navbar.top + navbar.height + 6) + 'px'">
			<!-- #ifdef MP-WEIXIN -->
			<view class="navbar" :style="'height: ' + (navbar.top + navbar.height + 6) + 'px;'">
				<view class="inner">
					<view class="search_box"
						:style="'top:' + navbar.top + 'px;height: ' + navbar.height + 'px;width:'+(navbar.customWidth?navbar.customWidth:267)+'px;left:'+(navbar.marginLeft?navbar.marginLeft:17)+'px;'">
						<view class="por_search">
							<view class="poa_scan" :style="'height: ' + navbar.height + 'px'">
								<view class="label" @tap="mesClick">
									{{ city }}
									<van-icon style="margin: 4rpx 10rpx 0" size="10px" name="/static/img/b_xl.png" />
								</view>
								<view class="search_line"></view>
								<view class="search_sc" :style="'padding: ' + (navbar.height - 24) / 2 + 'px'"
									@tap="visitSearch">
									<van-search readonly custom-class="search-round" placeholder="请输入您要搜索的内容"
										placeholder-style="font-size:24rpx" background="#f4f4f4" />
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- #endif -->
			<template v-if="loading == 1">
				<!-- 自定义banner组件 -->
				<my-swiper :swiper="swiper" @updateDot="updateDot" :dots="dots"></my-swiper>
				<view class="panel" style="margin-top: 26rpx; position: relative">
					<view class="home_top">
						<block>
							<view class="item">
								<van-icon size="40px" name="/static/images/zxgs.png" />
								<view class="ext">装修公司</view>
							</view>
							<view class="item" @tap="gosheji">
								<van-icon size="40px" name="/static/images/sheji.png" />
								<view class="ext">设计师</view>
							</view>
							<view class="item" @tap="gojiancai">
								<van-icon size="40px" name="/static/images/jiancai.png" />
								<view class="ext">本地商家</view>
							</view>
						</block>
					</view>
				</view>

				<view :class="'panel_box ' + (isFixedTop ? 'fixed_stk' : '')"
					:style="'top: ' + (isFixedTop ? navbarInitHeight - 18 : 0) + 'px'">
					<view class="panel_stk">
						<view style="border-top-left-radius: 10px; border-top-right-radius: 10px">
							<view class="kj_drop" v-if="iscityshow">
								<kj-dropdown :value="s_province" :options="province" @change="province_change">
								</kj-dropdown>
								<kj-dropdown :value="s_city" :options="cities" @change="city_change">
								</kj-dropdown>
								<kj-dropdown :value="zoneid" :options="zonelist" @change="zone_change">
								</kj-dropdown>
								<kj-dropdown :value="value1" :options="option1">
								</kj-dropdown>
							</view>
						</view>
					</view>
				</view>

				<view class="shop-list panel pannel_stb" :style="'margin-top: ' + (isFixedTop ? 30 : 0) + 'rpx;'">
					<!-- 数据列表组件 -->
					<my-goods-list :goodsList="goodsList" :isFixedTop="isFixedTop" @gocompanydetail="gocompanydetail"
						@followClick="followClick"></my-goods-list>
					<kj-loading ref="kjLoading" :loaddone_rec="loaddone||goodsListPages==0"></kj-loading>
					<!-- 推荐数据列表组件 -->
					<my-goods-list :goodsList="rec_list" :isFixedTop="isFixedTop" @gocompanydetail="gocompanydetail"
						@followClick="followClick"></my-goods-list>
					<!-- 加载loading -->
					<kj-loading ref="kjLoading" :loadmore="loadmore" :loaddone="loaddone"></kj-loading>
				</view>
			</template>

			<!-- 弹出地区选择 -->
			<view class="popup">
				<uni-popup ref="cityRef" background-color="#fff" type="center">
					<view class="popup-wrapper"
						style="background-color: #fff; width: 360px; padding: 30rpx; height: 600px; border-radius: 10rpx">
						<view style="text-align: center; padding-bottom: 30rpx; font-weight: bold">请选择城市</view>
						<view class="kj_drop kj_drop_pop" v-if="iscityshow">
							<kj-dropdown :value="s_province" :options="province" @change="province_change">
							</kj-dropdown>
							<kj-dropdown :value="s_city" :options="cities" @change="city_change">
							</kj-dropdown>
							<kj-dropdown :value="zoneid" :options="zonelist" @change="zone_change">
							</kj-dropdown>
						</view>
						<view class="submit-layer" @click="zoneSubmit">
							<van-button block type="default" color="#232773">
								确定
							</van-button>
						</view>
					</view>
				</uni-popup>
			</view>
		</view>
		<tab-bar ref="tabbar" :tabInd="1" :number="number" :v_count="v_count"></tab-bar>
	</view>
</template>
<script>
	import {
		getImage,
		getPage,
		getTabbar
	} from '../../utils/config';
	import api from '../../utils/api';
	import {
		http,
		storage,
		promisify,
		$toast,
		$loading,
		$query
	} from '../../utils/utils';
	import wxApi from '../../utils/wxApi';
	import {
		headerInfo
	} from '../../utils/env';
	let app = getApp();
	let {
		height,
		right,
		menuWidth
	} = headerInfo
	let leftStyle = `right: ${menuWidth / 2 / 2 + right}px`
	let tipTopStyle = `top: ${height}px;`
	let topStyle = `top: ${height + 10}px;`
	export default {
		data() {
			return {
				getImage: getImage,
				getPage: getPage,
				logged: 0,
				loading: 0,
				userId: 0,

				navbar: {
					top: '',
					height: ''
				},

				window: {},
				hfListIndex: 0,
				botZtListIndex: 0,
				timesHours: 0,
				guize: {},
				city: '',
				timesMinute: 0,
				timesSecond: 0,
				goodsNavFix: false,
				goodsNavType: 1,
				goodsList: [],
				goodsListPage: 1,
				goodsListPages: 0,
				loadmore: true,
				loaddone: false,
				rec_list: [],
				rec_pageindex: 0,
				rec_pages: 0,
				rec_loadmore: true,
				rec_loaddone: false,
				popupShow: false,
				popupShow1: false,
				popupShowTip: false,
				showwellcome: false,
				tipTopStyle: tipTopStyle,
				leftStyle: leftStyle,
				topStyle: topStyle,
				imgheights: {},
				curBannerHeight: 0,
				value1: 0,

				option1: [{
						text: '离我最近',
						value: 0
					},
					{
						text: '智能排序',
						value: 1
					},
					{
						text: '评分从高到低',
						value: 2
					}
				],

				s_province: 0,
				s_city: 0,
				regionInfo: [],
				province: [],
				cities: [],
				zonelist: [],
				zoneid: 0,
				abnor: false,
				navbarInitHeight: 0,

				//导航栏高度
				stkInitHeight: 0,

				//吸顶盒子高度
				isFixedTop: false,

				//是否固定顶部
				myTime: null,

				swiper: '',
				selected: 0,
				number: 0,
				dots: '',
				pickerArea: false,
				data: '',
				iscityshow: false,
				v_count:0
			};
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		onLoad(options) {
			/**
			 * 获取用户信息
			 */
			let logged;
			let userId = '';
			app.globalData
				.getLogin()
				.then((res) => {
					logged = res.code;
					userId = res.data.user.user_id;
				})
				.catch((res) => {
					logged = res;
				})
				.finally(() => {
					this.logged = logged
					this.userId = userId
				});
			console.log('~~~~~~~~~~~~onload', this.userId);
			//获取system信息
			promisify(uni.getSystemInfo)().then((res) => {
				//获取右上角胶囊信息
				// #ifdef MP-WEIXIN
				this.navbar = uni.getMenuButtonBoundingClientRect()
				console.log("--------------", this.navbar)
				// #endif

				//获取右上角胶囊信息
				// #ifdef MP-TOUTIAO
				let navbar = uni.getMenuButtonBoundingClientRect()
				let CustomButton = tt.getCustomButtonBoundingClientRect()
				navbar.customWidth = CustomButton.customNavigation.width - 10
				navbar.marginLeft = CustomButton.customNavigation.marginLeft + 5
				this.navbar = navbar
				// #endif

				// #ifdef APP-PLUS
				this.navbar = menuButton
				// #endif
				this.window = res
			});
			if (this.city == '' && app.globalData.zone) {
				this.city = app.globalData.zone.shortname
			}
			//第一部分数据加载
			http.post(
				api.default, {
					data: {
						action: 'getadsbanner',
						type: 2
					}
				},
				false
			).then((res) => {
				const {
					data
				} = res.data;
				this.swiper = data,
					this.loading = 1
			});
		},
		/**
		 * 页面滚动函数--监听页面滚动事件
		 */
		onPageScroll(e) {
			var that = this;
			uni.createSelectorQuery()
				.in(this)
				.select('.pannel_stb')
				.boundingClientRect(function(rect) {
					if (rect && rect.top > 0) {
						// 列表盒子距顶部的高度
						var listInTop = parseInt(rect.top);
						var isSatisfy = listInTop - that.stkInitHeight - that.navbarInitHeight < 0 ? true : false;
						//为了防止不停的setData, 这儿做了一个等式判断。 只有处于吸顶的临界值才会不相等
						if (that.isFixedTop === isSatisfy) {
							return false;
						}
						console.log('listInTop,stkInitHeight,navbarInitHeight', listInTop, that.stkInitHeight, that
							.navbarInitHeight);
						that.isFixedTop = isSatisfy
					}
				})
				.exec();
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady() {
			let that = this;
			setTimeout(() => {
				if (that.navbarInitHeight == 0) {
					uni.createSelectorQuery()
						.in(this)
						.select('.navbar')
						.boundingClientRect(function(rect) {
							if (rect && rect.height > 0) {
								var navbarInitHeight = parseInt(rect.height);
								that.navbarInitHeight = navbarInitHeight
							}
						})
						.exec();
				}
				if (that.stkInitHeight == 0) {
					uni.createSelectorQuery()
						.in(this)
						.select('.panel_stk')
						.boundingClientRect(function(rect) {
							if (rect && rect.height > 0) {
								var stkInitHeight = parseInt(rect.height);
								that.stkInitHeight = stkInitHeight
							}
						})
						.exec();
				}
			}, 100);
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {
			app.globalData.getLogin().then((res) => {
				const {
					user
				} = res.data;
				this.userId = user.user_id
				console.log('~~~~~~~~~~~~onshow-if', this.userId);
				if (this.userId) {
					this.myTime = setInterval(function() {
						this.number = app.globalData.unReadMsg
					}, 5000)
				}
			});
			this.v_count = app.globalData.v_count;
			//console.log('onShow------------',app.globalData)
			if (app.globalData.zone) {
				this.getRegionInfo().then((res) => {
					//地区格式化
					//this.formatArea();
					let province = [];
					let city1 = [{
						text: '请选择',
						value: 0
					}];
					var zones = [{
						text: '全部',
						value: 0
					}];
					var temp = app.globalData.zone.region_path.substring(1, app.globalData.zone.region_path
						.length - 1).split(',');
					console.log(temp);
					var s_province = parseInt(temp[0]);
					var s_city = 0;
					if (temp.length >= 2) {
						s_city = parseInt(temp[1]);
					}
					var zoneid = 0;
					if (temp.length == 3) {
						zoneid = parseInt(temp[2]);
					}
					res.forEach((item, index) => {
						province.push({
							text: item.name,
							value: item.id
						});
						if (item.id == s_province) {
							var cities = item.list;
							cities.forEach((c, i) => {
								city1.push({
									text: c.name,
									value: c.id
								});
								if (s_city == c.id) {
									var zonelist = c.list;
									zonelist.forEach((z, j) => {
										zones.push({
											text: z.name,
											value: z.id
										});
									});
								}
							});
						}
					});
					console.log(s_city);
					this.province = province
					this.s_province = s_province
					this.cities = city1
					this.s_city = s_city
					this.zonelist = zones
					this.zoneid = zoneid
					this.iscityshow = false
					this.$nextTick(() => {
						this.iscityshow = true
					})
					//加载产品列表
					this.getProductsInfo((res) => {
						console.log(res);
						this.goodsList = res.list
						this.loadmore = false
						if (this.loaddone || this.goodsListPages == 0) {
							this.rec_pageindex = 1
							this.rec_pages = 0
							this.getRecShopList((res1) => {
								this.rec_list = res1.list
								this.rec_loadmore = false
							});
						}
					});
				});
			} else {
				uni.reLaunch(getPage.home);
			}
		},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide() {
			console.log('user_onHide________清除定时器~');
			clearInterval(this.myTime);
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {
			uni.showLoading({
				title: '加载中...'
			});
			this.goodsListPage = 1
			//加载产品列表
			this.getProductsInfo((res) => {
				console.log(res);
				this.goodsList = res.list
				this.loadmore = false
				if (this.loaddone || this.goodsListPages == 0) {
					this.rec_pageindex = 1
					this.rec_pages = 0
					this.getRecShopList((res1) => {
						this.rec_list = res1.list
						this.rec_loadmore = false
					});
				}
				uni.stopPullDownRefresh();
				uni.hideLoading();
			});
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {
			let {
				goodsListPage,
				goodsListPages,
				loadmore,
				rec_pageindex,
				rec_pages,
				rec_loadmore
			} = this;
			//未请求完且未在加载中
			if (goodsListPages > goodsListPage && !loadmore) {
				goodsListPage++;
				loadmore = true;

				//显示加载效果
				this.goodsListPage = goodsListPage
				this.loadmore = loadmore
				uni.showNavigationBarLoading();

				//请求数据
				this.getProductsInfo((res) => {
					let {
						goodsList
					} = this;
					loadmore = false;
					this.loadmore = loadmore
					this.goodsList = goodsList.concat(res.list)
					//隐藏加载效果
					uni.hideNavigationBarLoading();
				});
			} else {
				console.log('底部--------rec_pages=', rec_pages);
				console.log('底部------rec_pageindex=', rec_pageindex);
				console.log('底部-------rec_loadmore=', rec_loadmore);
				if (rec_pageindex == 0) {
					rec_loadmore = false;
				}
				if (rec_pages >= rec_pageindex && !rec_loadmore) {
					rec_pageindex++;
					rec_loadmore = true;

					//显示加载效果
					this.rec_pageindex = rec_pageindex
					this.rec_loadmore = rec_loadmore
					uni.showNavigationBarLoading();

					//请求数据
					this.getRecShopList((res) => {
						let {
							rec_list
						} = this;
						rec_loadmore = false;
						this.rec_loadmore = rec_loadmore
						this.rec_list = rec_list.concat(res.list)
						//隐藏加载效果
						uni.hideNavigationBarLoading();
					});
				}
			}
		},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {
			if (this.userId > 0) {
				pageshare += '?pid=' + this.userId;
			}
			return {
				title: ``,
				imageUrl: '',
				path: pageshare,
				success: function(res) {
					console.log('分享');
					//$toast(pageshare);
					if (res.errMsg == 'shareAppMessage:ok') {
						//转发成功
						$toast(pageshare);
						console.log('分享成功');
						if (res.hasOwnProperty('shareTickets')) {
							//分享到群
						} else {
							// 分享到个人
						}
					} else {
						//转发失败
						console.log('分享失败');
					}
				}
			};
		},
		methods: {
			setToggle(property) {
				this[property] = !this[property]
			},

			handleNotouch() {
				return false;
			},

			/**
			 * 获取地区
			 */
			getRegionInfo() {
				return new Promise((resolve) => {
					storage
						.get('regionInfo')
						.then((res) => {
							this.regionInfo = res
							this.pickerArea = false
							console.log('getRegionInfo----------', this.regionInfo);
							resolve(res);
						})
						.catch((res) => {
							http.get(
								api.default, {
									data: {
										action: 'district'
									}
								},
								false
							).then((res) => {
								const {
									data
								} = res.data;
								this.regionInfo = data
								this.pickerArea = false
								storage.set('regionInfo', data);
								resolve(data);
							});
						});
				});
			},

			imageLoad: function(e) {
				//获取图片真实宽度
				var imgwidth = e.detail.width;
				var imgheight = e.detail.height;
				var //宽高比
					ratio = imgwidth / imgheight; //计算的高度值
				var viewHeight = 750 / ratio;
				var imgheight = viewHeight;
				var imgheights = this.imgheights;
				//把每一张图片的对应的高度记录到数组里
				imgheights[e.target.dataset.id] = imgheight;
				this.imgheights = imgheights
			},

			updateDot(data) {
				let dots = data.detail.dots;
				this.dots = dots
			},

			shopchange: function(e) {
				this.curshop = e.detail.current
			},

			handlePopupClose() {
				this.popupShow = false
			},

			handlePopupShare() {
				this.popupShow1 = true
				this.popupShowTip = false
			},

			handlePopupCloseTip() {
				this.popupShow1 = false
			},

			pingtai() {
				this.popupShow = true
			},

			gocompanydetail(e) {
				console.log('eee', e);
				const data = e.detail.data || e.currentTarget.dataset;
				console.log('data===================', data);
				if (data.id) {
					wxApi.navigateTo(getPage.companydetail, {
						id: data.id,
						distance: data.distance
					});
				}
			},

			goActiveShop() {
				let {
					ID
				} = this.activedData;
				wxApi.navigateTo(getPage.activeShop, {
					aid: ID
				});
			},

			goCouponpro() {
				wxApi.navigateTo(getPage.couponProduct);
			},

			gotest() {
				wxApi.navigateTo('/subPackages/pages/yaoqinguser/yaoqinguser', {
					shopName: 'xz',
					shopid: 2634,
					img: api.imageCdn + 'users/m17240605530004882.png'
				});
			},

			gocompanydetailCur(e) {
				const data = e.currentTarget.dataset;
				if (data.id) {
					wxApi.navigateTo(getPage.companydetail, {
						id: data.id,
						distance: data.distance
					});
				}
			},

			/**
			 * 密码修改--网络请求
			 */
			zoneSubmit(e) {
				var zoneid = this.zoneid;
				var cityid = this.s_city;
				var provinceid = this.s_province;
				const {
					regionInfo
				} = this;
				if (zoneid > 0 || cityid > 0 || provinceid > 0) {
					app.globalData.zoneid = zoneid ? zoneid : cityid ? cityid : provinceid;
					console.log('zoneSubmit==================zoneid=', app.globalData.zoneid);
					//获取设置城市id
					http.post(
						api.default, {
							data: {
								action: 'getregioninfo',
								id: app.globalData.zoneid
							}
						},
						false
					).then((res) => {
						const {
							data
						} = res.data;
						if (data != null) {
							app.globalData.zone = data;
							if (e != undefined) {
								this.$refs.cityRef.close()
							}
							this.city = app.globalData.zone.shortname
							this.getProductsInfo((res) => {
								this.goodsList = res.list
								this.loadmore = false
								if (this.loaddone || res.list.length == 0) {
									this.rec_pageindex = 1
									this.rec_pages = 0
									this.getRecShopList((res1) => {
										this.rec_list = res1.list
										this.rec_loadmore = false
									});
								}
							});
							this.getActivedList();
						}
					});
				} else {
					$toast('请选择城市');
				}
			},

			mesClick(e) {
				console.log('eeeeeeeeee', e)
				//wxApi.navigateTo("/pages/location/index");
				this.$refs.cityRef.open()
			},

			gochoujiang() {
				wxApi.navigateTo(getPage.choujiang);
			},

			gojifen(e) {
				const data = e.currentTarget.dataset || e.target.dataset;
				const url = data.url;
				if (url.indexOf('http') > -1) {
					wxApi.navigateTo('/pages/web/web?id=' + url);
				} else {
					wxApi.navigateTo(url);
				}
			},

			/**
			 * swiper 记录当前值
			 */
			hfListChange(e) {
				this.hfListIndex = e.detail.current
			},

			botZtListChange(e) {
				this.botZtListIndex = e.detail.current
			},

			/**
			 * 搜索
			 */
			visitSearch() {
				wxApi.navigateTo(getPage.search);
			},

			gosheji() {
				wxApi.navigateTo('/pages/designer/designer');
			},

			gomdhd() {
				console.log(getPage.mdhd);
				wxApi.redirectTo(getPage.mdhd);
			},

			gozhuangxiu() {
				console.log(getPage.customer);
				wxApi.redirectTo(getPage.mfsheji);
				// wxApi.navigateTo(getPage.mfsheji);
				// wxApi.redirectTo(getPage.customer);
			},

			gojiancai() {
				wxApi.navigateTo(getPage.zhucai);
			},

			golink(e) {
				console.log('eeeeee', e);
				const data = e.currentTarget.dataset || e.target.dataset;
				//转为小写并去除左右空格
				var str = data.url.toLowerCase();
				if (str != '') {
					if (str.indexOf('https') === 0 || str.indexOf('http') === 0) {
						wxApi.navigateTo('/pages/web/web?id=' + str);
					} else if (str.indexOf('mm://') == 0) {
						var array = str.split('_');
						if (array[0].replace('mm://', '') == 'shop') {
							wxApi.navigateTo(getPage.companydetail, {
								id: array[1]
							});
						}
					} else if (str.indexOf('ym://') == 0) {
						var url = str.replace('ym://', '');
						wxApi.navigateTo(url);
					} else {
						wxApi.navigateTo('/pages/goods/goods?id=' + str);
					}
				}
			},

			// 获取活动数据
			getActivedList() {
				let {
					userId,
					s_city,
					zoneid,
					s_province
				} = this;
				var latitude = 0;
				var longitude = 0;
				var mylocation = null;
				if (uni.getStorageSync('mylocation') == '' && app.globalData.zone == null) {
					//wxApi.navigateTo("/pages/location/index");
					this.$refs.cityRef.open()
					return;
				} else if (uni.getStorageSync('mylocation') != '') {
					mylocation = JSON.parse(uni.getStorageSync('mylocation'));
					latitude = mylocation.latitude;
					longitude = mylocation.longitude;
				} else {
					latitude = app.globalData.zone.lat;
					longitude = app.globalData.zone.lng;
				}
				http.post(
					api.default, {
						data: {
							action: 'getactivitydata',
							latitude: latitude,
							longitude: longitude,
							userid: userId,
							cityid: s_city,
							zoneid: zoneid,
							provinceid: s_province
						}
					},
					false
				).then((res) => {
					const {
						data
					} = res.data;
					this.shop_list = data.shoplist
					// this.product_list = data.productlist
					this.discountshoplist = data.discountshoplist
					this.activedData = data.ms
				});
			},

			/**
			 * 获取产品数据
			 */
			getProductsInfo(cb, a = false) {
				let {
					goodsNavType,
					goodsListPage,
					goodsListPages,
					loaddone,
					abnor,
					userId,
					s_city,
					zoneid,
					s_province
				} = this;
				console.log('getProductsInfo---------s_province=', s_province);
				console.log('getProductsInfo---------s_city=', s_city);
				console.log('getProductsInfo---------zoneid=', zoneid);
				var latitude = 0;
				var longitude = 0;
				var mylocation = null;
				if (uni.getStorageSync('mylocation') == '' && app.globalData.zone == null) {
					//wxApi.navigateTo("/pages/location/index");
					this.$refs.cityRef.open()
					return;
				} else if (uni.getStorageSync('mylocation') != '') {
					mylocation = JSON.parse(uni.getStorageSync('mylocation'));
					latitude = mylocation.latitude;
					longitude = mylocation.longitude;
				} else {
					latitude = app.globalData.zone.lat;
					longitude = app.globalData.zone.lng;
				}
				http.post(
					api.default, {
						data: {
							action: 'GetShopList',
							pagesize: 10,
							pageindex: goodsListPage,
							latitude: latitude,
							longitude: longitude,
							userid: userId,
							cityid: s_city,
							zoneid: zoneid,
							provinceid: s_province,
							pagetype: 'home'
						}
					},
					a
				).then((res) => {
					const {
						data
					} = res.data;
					//是否加载完毕

					if (data.pages == 0) {
						abnor = true;
					} else {
						abnor = false;
					}
					if (goodsListPage == data.pages && !abnor) {
						loaddone = true;
					}
					this.goodsListPages = data.pages
					this.loaddone = loaddone
					this.abnor = abnor
					console.log('getProductsInfo------------', goodsListPages);
					if (cb) {
						cb(data);
					}
				});
			},

			getRecShopList(cb, a = false) {
				let {
					rec_pageindex,
					rec_pages,
					rec_loaddone,
					userId,
					s_city,
					zoneid,
					s_province
				} = this;
				var mylocation = JSON.parse(uni.getStorageSync('mylocation'));
				http.post(
					api.default, {
						data: {
							action: 'GetRecShopList',
							pagesize: 20,
							pageindex: rec_pageindex,
							nocityid: s_city,
							nozoneid: zoneid,
							latitude: mylocation.latitude,
							longitude: mylocation.longitude,
							userid: userId,
							provinceid: s_province,
							pagetype: 'home'
						}
					},
					a
				).then((res) => {
					const {
						data
					} = res.data;
					//是否加载完毕
					if (rec_pageindex == data.pages) {
						rec_loaddone = true;
					}
					this.rec_pages = data.pages
					this.rec_loaddone = rec_loaddone
					if (cb) {
						cb(data);
					}
				});
			},

			/**
			 * 跳转登录
			 */
			goLogin() {
				wxApi.setStartPage();
				wxApi.navigateTo(getPage.login);
			},

			formatArea() {
				let {
					regionInfo,
					province
				} = this;
				province = [];
				regionInfo.forEach((item, index) => {
					province.push({
						text: item.name,
						value: item.id
					});
				});
				var cities = regionInfo[0].list;
				var city = [{
					text: '请选择',
					value: 0
				}];
				cities.forEach((c, i) => {
					city.push({
						text: c.name,
						value: c.id
					});
				});
				var zonelist = cities[0].list;
				var zones = [{
					text: '全部',
					value: 0
				}];
				zonelist.forEach((c, i) => {
					zones.push({
						text: c.name,
						value: c.id
					});
				});
				this.province = province
				this.s_province = province[0].value
				this.cities = city
				this.zonelist = zones
				this.zoneid = 0
			},

			province_change(e) {
				var id = e;
				const {
					regionInfo
				} = this;
				let city = [{
					text: '请选择',
					value: 0
				}];
				var cityname = '';
				regionInfo.forEach((item, index) => {
					if (item.id == id) {
						cityname = item.name.replace('省', '').replace('市', '');
						var cities = item.list;
						cities.forEach((c, i) => {
							city.push({
								text: c.name,
								value: c.id
							});
						});
					}
				});
				this.cities = city
				this.s_city = 0
				this.s_province = id
				this.city = cityname
				this.iscityshow = false
				this.$nextTick(() => {
					this.iscityshow = true
				})
				this.zoneSubmit();
			},

			city_change(e) {
				var cityid = e;
				console.log('city_change-------------', e.detail);
				let zone = [{
					text: '全部',
					value: 0
				}];
				var city = '';
				if (cityid == 0) {
					this.province.forEach((item, index) => {
						if (item.value == this.s_province) {
							city = item.text.replace('省', '').replace('市', '');
						}
					});
				}
				this.regionInfo.forEach((item, index) => {
					if (item.id == parseInt(this.s_province)) {
						var cities = item.list;
						cities.forEach((c, i) => {
							if (c.id == parseInt(cityid)) {
								var c_zone = c.list;
								city = c.name.replace('市', '');
								c_zone.forEach((z, j) => {
									zone.push({
										text: z.name,
										value: z.id
									});
								});
							}
						});
					}
				});
				this.loadmore = false
				this.s_city = cityid
				this.zonelist = zone
				this.city = city
				this.zoneid = 0
				this.goodsListPage = 1
				this.iscityshow = false
				this.$nextTick(() => {
					this.iscityshow = true
				})
				this.zoneSubmit();
			},

			zone_change(e) {
				var zoneid = e;
				var city = this.city;
				console.log('zone_change-------', city);
				if (zoneid > 0) {
					this.zonelist.forEach((item, index) => {
						if (item.value == zoneid) {
							city = item.text.replace('区', '').replace('县', '');
						}
					});
				} else {
					this.cities.forEach((item, index) => {
						if (item.value == this.s_city) {
							city = item.text.replace('市', '');
						}
					});
				}
				this.zoneid = zoneid
				this.city = city
				this.goodsListPage = 1
				console.log('zone_change-------getProductsInfo');
				this.zoneSubmit();
			},

			godesignerdetail(e) {
				const data = e.currentTarget.dataset;
				if (data.id) {
					wxApi.navigateTo(getPage.companydetail, {
						id: data.id
					});
				}
			},

			/**
			 * 关注店铺
			 */
			followClick(event) {
				let {
					isfav,
					ShopId
				} = event.detail;
				var {
					logged,
					userId
				} = this;
				if (logged) {
					http.post(api.default, {
						data: {
							action: 'fav_shop',
							userid: userId,
							shopid: ShopId
						}
					}).then((res) => {
						let {
							errmsg,
							data
						} = res.data;
						$toast(errmsg, {
							icon: 'success'
						});
						// 前端显示跟新收藏状态
						let goodsArr = this.goodsList;
						goodsArr.forEach((item) => {
							if (item.ShopId == ShopId) {
								item.isfav = data;
							}
						});
						this.goodsList = goodsArr
					});
				} else {
					this.goLogin();
				}
			},

			// 获取navbar盒子高度
			getnavboxheight() {
				let that = this;
				uni.createSelectorQuery()
					.in(this)
					.select('.navbar')
					.boundingClientRect(function(rect) {
						if (rect && rect.height > 0) {
							var navbarInitHeight = parseInt(rect.height);
							that.navbarInitHeight = navbarInitHeight
						}
					})
					.exec();
			},

			// 获取粘性盒子高度
			getstkboxheight() {
				let that = this;
				uni.createSelectorQuery()
					.in(this)
					.select('.panel_stk')
					.boundingClientRect(function(rect) {
						if (rect && rect.height > 0) {
							var stkInitHeight = parseInt(rect.height);
							that.stkInitHeight = stkInitHeight
						}
					})
					.exec();
			},

			// 获取未读消息数
			getunreadmsg() {
				http.post(
					api.default, {
						data: {
							action: 'getunreadmsgcount',
							userid: this.userId
						}
					},
					false
				).then((res) => {
					console.log('未读消息=', res);
					console.log('this=', this);
					app.globalData.unReadMsg = res.data.data;
					this.number = res.data.data;
				});
			},

			//连接WebSocket服务器
			connectWebSocket: function() {
				var that = this;
				uni.connectSocket({
					url: ChatConfig.CIM_URI,
					success: function(res) {
						console.log('WebSocket连接成功');
					},
					fail: function(res) {
						console.log('WebSocket连接失败:', res);
					}
				});
				uni.onSocketOpen(function(res) {
					console.log('WebSocket连接已打开');
					that.socketOpen = true
					for (var i = 0; i < that.socketMsgQueue.length; i++) {
						that.sendSocketMessage(that.socketMsgQueue[i]);
					}
					that.socketMsgQueue = []
					that.innerOnConnectFinished();
				});
				uni.onSocketError(function(res) {
					console.log('WebSocket连接打开失败:', res);
				});
				uni.onSocketClose(function(res) {
					console.log('离开页面--------');
					console.log('WebSocket连接已关闭:', res);
					that.socketOpen = false
					// that.innerOnConnectionClosed(res);
				});
				uni.onSocketMessage(function(res) {
					console.log('接收到服务器发送的数据:', res.data);
					that.innerOnMessageReceived(res);
					// var messages = that.data.messages
					// messages.push(res.data)
					// that.messages = messages
					// that.scrollIntoView = 'message-' + messages.length
				});
			},

			innerOnConnectFinished: function() {
				let account = '';
				if (account === '' || account === undefined) {
					this.onConnectFinished();
				} else {
					this.bindAccount(account);
				}
			},

			onConnectFinished: function() {
				//获取当前登录用户
				app.globalData.getLogin().then((res) => {
					console.log(res);
					this.bind(res.data.user.user_id);
				});
			},

			bind: function(account) {
				storage.set('account', account);
				let deviceId = ''; //storage.get('deviceId');
				if (deviceId === '' || deviceId === undefined) {
					deviceId = this.generateUUID();
					storage.set('deviceId', deviceId);
				}
				let browser = '微信小程序';
				let body = {};
				body.key = ChatConfig.KEY_CLIENT_BIND;
				body.timestamp = new Date().getTime();
				body.data = {};
				body.data.uid = account;
				body.data.channel = ChatConfig.APP_CHANNEL;
				body.data.appVersion = ChatConfig.APP_VERSION;
				body.data.packageName = ChatConfig.APP_PACKAGE;
				body.data.deviceId = deviceId;
				body.data.deviceName = browser;
				console.log(body);
				this.sendRequest(body);
			},

			sendRequest: function(body) {
				let data = {};
				data.type = ChatConfig.SENT_BODY;
				data.content = JSON.stringify(body);
				this.sendSocketMessage(JSON.stringify(data));
			},

			innerOnMessageReceived(e) {
				console.log(e);
				let data = JSON.parse(e.data);
				let type = data.type;
				let body = data.content;
				if (type === ChatConfig.PING) {
					this.pong();
					return;
				}
				if (type === ChatConfig.MESSAGE) {
					let message = JSON.parse(body);
					this.onInterceptMessageReceived(message);
					return;
				}
				if (type === ChatConfig.REPLY_BODY) {
					let reply = JSON.parse(body);
					/*
					 * 判断是否是握手鉴权失败
					 * 终止后续自动重连
					 */
					if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
						this.manualStop = true
					}
					this.onReplyReceived(reply);
				}
			},

			pong: function() {
				let data = {};
				data.type = ChatConfig.PONG;
				data.content = ChatConfig.PONG_BODY;
				this.sendSocketMessage(JSON.stringify(data));
			},

			onInterceptMessageReceived(message) {
				/*
				 *被强制下线之后，不再继续连接服务端
				 */
				if (message.action === ChatConfig.ACTION_999) {
					this.manualStop = true
				}
				app.globalData.unReadMsg++;
				this.number = app.globalData.unReadMsg
				console.log('++++', app.globalData.unReadMsg);
			},

			onReplyReceived(reply) {
				console.log(reply);
				if (reply.key === ChatConfig.KEY_CLIENT_BIND && reply.code === ChatConfig.CODE_OK) {
					console.log('登录成功');
					// hideProcess();

					// $('#LoginDialog').fadeOut();

					// $('#MessageDialog').fadeIn();
					// $('#MessageDialog').addClass("in");
					// $("#current_account").text($('#account').val());
				}

				/**
				 * 链接鉴权失败
				 */
				if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
					//hideProcess();
					console.log('鉴权失败');
				}
			},

			innerOnConnectionClosed: function(e) {
				var that = this;
				if (!that.manualStop) {
					let time = Math.floor(Math.random() * 16 + 15);
					setTimeout(function() {
						console.log('Socket重新连接');
						that.connectWebSocket(); //重新连接
					}, time);
				}
			},

			generateUUID() {
				let d = new Date().getTime();
				let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					let r = (d + Math.random() * 16) % 16 | 0;
					d = Math.floor(d / 16);
					return (c === 'x' ? r : (r & 3) | 8).toString(16);
				});
				return uuid.replace(/-/g, '');
			},

			// 发送WebSocket消息
			sendSocketMessage: function(message) {
				if (this.socketOpen) {
					uni.sendSocketMessage({
						data: message
					});
				} else {
					this.socketMsgQueue.push(message);
				}
			},
		}
	};
</script>
<style scoped>
	@import './company.css';
</style>
